/**
 * 浏览器BOM工具类
 */
import { isExternal } from '../validate'

// 获取URL查询参数值
export function getQuery(name: string) {
	const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
	const r = window.location.search.substr(1).match(reg)
	if (r != null) return unescape(r[2])
	return null
}

// 序列化URL查询参数
export function qs(data: any) {
	let res = ''
	for (const key in data) {
		res += encodeURIComponent(key) + '=' + encodeURIComponent(data[key]) + '&'
	}
	if (res.length > 0) {
		res = '?' + res.substring(0, res.length - 1)
	}
	return res
}

// 打开Url
export function openUrl(url: string, type = '_blank') {
	if (isExternal(url)) {
		window.open(url, type)
	}
}

// 下载Url
export function downloadUrl(url: string, filename = '') {
	const downloadLink = document.createElement('a')
	downloadLink.target = '_blank'
	downloadLink.download = filename
	downloadLink.style.display = 'none'
	downloadLink.href = url
	downloadLink.setAttribute('download', filename)
	document.body.appendChild(downloadLink)
	downloadLink.click()
	document.body.removeChild(downloadLink)
}

// 下载Url
export async function downloadBlob(res: any, filename = '') {
	// let content = res
	// if (filename.endsWith('.csv')) {
	//   content = new Blob(['\ufeff' + (await res.text())], {
	//     type: 'text/csv,charset=UTF-8'
	//   })
	// }
	const fileURL = window.URL.createObjectURL(res)
	const downloadLink = document.createElement('a')
	downloadLink.href = fileURL
	downloadLink.setAttribute('download', filename)
	document.body.appendChild(downloadLink)
	downloadLink.click()
	document.body.removeChild(downloadLink)
}

// 返回上个路由
export function back() {
	window.history.back()
}

export function changeFavicon(url: string, id = 'favicon') {
	const dom = document.querySelector(`#${id}`)
	url && dom && dom.setAttribute('href', url)
}

export function changeTitle(title: string) {
	document.title = title
}

export function getFullPath() {
	const { href, host } = window.location
	const arr = href.split(host)
	return arr.length === 2 ? arr[1] : ''
}

export function isPC() {
	return !/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
}

export function getOS() {
	if (navigator.userAgent.indexOf('Window') > 0) {
		return 'Windows'
	} else if (navigator.userAgent.indexOf('Mac OS X') > 0) {
		return 'Mac'
	} else if (navigator.userAgent.indexOf('Linux') > 0) {
		return 'Linux'
	} else {
		return ''
	}
}
